import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  Animated,
  TextInput,
  TouchableOpacity,
} from 'react-native';
import styles from './indexStyle';
import api from '../../services/api';
import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';
import CountDownText from '../global/countDown/CountDownText';
import KeyboardAwareScrollView from '../global/keyboardScrollView/KeyboardAwareScrollView';
import dismissKeyboard from 'dismissKeyboard';

class RegIndex extends Component {
    constructor(props) {
		super(props);

		this.state = {
            isShowPass: false,
            checked: true,
            loadingShow: false,
            phone:"",
            passwd:"",
            hk_name:"",
            code:'',
            interval:false,
		};

		// this._getTabHeight = this._getTabHeight.bind(this);
		// this._onChangeTab = this._onChangeTab.bind(this);

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentWillMount() {
		// this._retrieveDetails();
	}

    async _submitAction(){
        let {phone, passwd, hk_name, code, checked} = this.state;
        let {navigator} = this.props;

        if(!phone){
             this.refs.toast.show('请输入手机号',2000);
             return;
        }

        if(!/^1[0-9]{10}$/.test(phone)){
            this.refs.toast.show('请输入正确的手机号',2000);
            return;
        }

        if(!hk_name){
             this.refs.toast.show('请输入管家的昵称',2000);
             return;
        }

        if(hk_name.length < 1 || hk_name.length > 16){
             this.refs.toast.show('用户名请输入1~16个字符',2000);
             return;
        }

        if(passwd.length == 0 || passwd.match(/^\s+$/g)){
             this.refs.toast.show('密码为空，或者全是空格',2000);
             return;
        }

        if(passwd.length > 16 || passwd.length < 6){//是否符合密码规范
             this.refs.toast.show('密码请输入6-16个字符',2000);
             return;
        }

        if(/.*[\u4e00-\u9fa5]+.*$/.test(passwd)){//判断是否有汉字
            this.refs.toast.show('密码不能包含汉字',2000);
            return;
        }

        if(!code){
             this.refs.toast.show('请输入验证码',2000);
             return;
        }

        if(!checked){
             this.refs.toast.show('请先同意注册协议',2000);
             return;
        }

        this.setState({loadingShow: true});
        let res = await api.post("/housekeeper/checkregparams",{phone,passwd,hk_name,code});
        this.setState({loadingShow: false});
        if(res.cd == 1){
            this.refs.toast.show(res.msg);
            return;
        }else{
            navigator.push({
                title: "管家-注册",
                backButtonTitle:'',
    			screen: 'housekeeperapp.regsecondstep',
    			passProps: {
                    phone,
                    passwd,
                    hk_name,
                    code
    			},
                navigatorStyle:{
                    navBarHidden: false,
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                	navBarButtonColor: 'white',
                	navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true
                },
                navigatorButtons: {
                    leftButtons:[
                        {
                            id: 'back',
                            icon: require("../../../img/hk_back_icon.png")
                        }
                    ]
                }
    			// backButtonHidden: true,
    		});
        }
    }

    _showPass(){
        let {isShowPass} = this.state;

        this.setState({
            isShowPass: !isShowPass
        });
    }

    _checkBox(){
        let {checked} = this.state;

        this.setState({
            checked: !checked
        });
    }

    async _sendCode(){
        let {phone} = this.state;

        if(!phone){
             this.refs.toast.show('请输入手机号',2000);
             return;
        }

        if(!/^1[0-9]{10}$/.test(phone)){
            this.refs.toast.show('请输入正确的手机号',2000);
            return;
        }

        if(this.state.interval){
            return;
        }

        this.setState({loadingShow: true});
        let res = await api.post("/housekeeper/regSendCode",{phone,type:"REG"});
        this.setState({loadingShow: false, interval:true});
        if(res.cd == 1){
            this.setState({interval:false});
            this.refs.toast.show(res.msg,2000);
            return;
        }

        if(!res.data || res.data.status_code != "OK"){
            this.setState({interval:false});
            if(res.data.status_code == 'isv.BUSINESS_LIMIT_CONTROL'){
                this.refs.toast.show("发送频繁，请稍后重试",2000);
            }else if(res.data.status_code == 'isv.MOBILE_NUMBER_ILLEGAL'){
                this.refs.toast.show("手机号码格式错误",2000);
            }else{
                this.refs.toast.show("发送验证码失败",2000);
            }
			return;
		}

        this.refs.countDownText.start();
        this.refs.toast.show("验证码已发送到您的手机\n10分钟内输入有效", 2000);

        // this.setState({code: res.msg});
        console.log("##", res);
    }

    _refreshCodeText(sec){
        return sec + '秒后重新获取';
    }

    _showUserAgreement(){
        let {navigator} = this.props;
        navigator.push({
            title: "注册协议",
            backButtonTitle:'',
            screen: 'housekeeperapp.agreewebview',
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
                navBarButtonColor: 'white',
                navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ]
            }
            // backButtonHidden: true,
        });
    }

    _loginAction(){
        this.props.navigator.pop();
    }

    render() {
        return (
            <View style={[styles.container,{backgroundColor:'#f3f3f3'}]} onStartShouldSetResponderCapture={(e) => {
                const focusField = TextInput.State.currentlyFocusedField();
                if (focusField != null && e.nativeEvent.target != focusField){
                    dismissKeyboard();
                }
            }}>
                <KeyboardAwareScrollView
                    style={styles.scrollContainer}
                    extraScrollHeight={60}>

                    <View style={styles.toolsContainer}>
                        <View style={styles.addBtn}>
                            <Text style={styles.titleText}>手机号</Text>
                            <TextInput
                                defaultValue={""}
                                autoFocus={false}
                                style={styles.centerInput}
                                editable = {true}
                                clearButtonMode={'while-editing'}
                                secureTextEntry={false}
                                keyboardType={'numeric'}
                                maxLength={11}
                                onChangeText={(text)=>{this.setState({phone:text})}}
                                underlineColorAndroid={'transparent'}
                                placeholder={'请输入手机号'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        </View>
                        <View style={styles.addBtn}>
                            <Text style={styles.titleText}>用户名</Text>
                            <TextInput
                                defaultValue={""}
                                clearButtonMode={'while-editing'}
                                style={styles.centerInput}
                                editable = {true}
                                secureTextEntry={false}
                                onChangeText={(text)=>{this.setState({hk_name:text})}}
                                underlineColorAndroid={'transparent'}
                                placeholder={'请输入管家的昵称'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        </View>
                        <View style={styles.addBtn}>
                            <Text style={styles.titleText}>验证码</Text>
                            <TextInput
                                style={styles.centerInput}
                                editable = {true}
                                clearButtonMode={'while-editing'}
                                value={this.state.code}
                                onChangeText={(text)=>{this.setState({code:text})}}
                                underlineColorAndroid={'transparent'}
                                placeholder={'请输入验证码'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        <TouchableOpacity onPress={this._sendCode.bind(this)}>
                                <CountDownText
                                    style={styles.sendCodeText}
                                    disabledStyle={styles.disableSendCodeText}
                                    countType='seconds'
                                    ref='countDownText'
                                    afterEnd={() => {this.setState({interval:false})}}
                                    timeLeft={59}
                                    step={-1}
                                    startText='获取验证码'
                                    endText='获取验证码'
                                    auto={false}
                                    intervalText={this._refreshCodeText.bind(this)}
                                />
                            </TouchableOpacity>
                        </View>
                        <View style={[styles.addBtn,{borderBottomWidth:0,paddingRight:0}]}>
                            <Text style={styles.titleText}>密码</Text>
                            <TextInput
                                style={styles.centerInput}
                                editable = {true}
                                secureTextEntry={!this.state.isShowPass}
                                underlineColorAndroid={'transparent'}
                                onChangeText={(text)=>{this.setState({passwd:text})}}
                                placeholder={'请输入6-16个字符'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                            <TouchableOpacity onPress={this._showPass.bind(this)} style={{padding:15}}>
                                <Image source={this.state.isShowPass?require('../../../img/hk_login_openeye_icon.png'):require('../../../img/hk_login_closeeye_icon.png')} style={styles.rightImage}/>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={styles.agreementContainer}>
                        <TouchableOpacity onPress={this._checkBox.bind(this)} style={{marginRight:10}}>
                            <Image source={this.state.checked?require('../../../img/hk_checkbox_selected_icon.png'):require('../../../img/hk_checkbox_icon.png')} />
                        </TouchableOpacity>
                        <Text style={styles.subAgreementInfo}>同意管家来了</Text>
                        <TouchableOpacity onPress={this._showUserAgreement.bind(this)}>
                            <Text style={styles.agreementText}>《注册协议》</Text>
                        </TouchableOpacity>
                    </View>

                    <TouchableOpacity onPress={this._submitAction.bind(this)} style={styles.submitActionPhoneBtn}>
                        <Text style={styles.submitActionText}>下一步</Text>
                    </TouchableOpacity>
                    <View style={[styles.agreementContainer,{justifyContent:'center',marginTop:60}]}>
                        <Text style={[styles.subAgreementInfo,{fontSize:15}]}>已有账号，</Text>
                        <TouchableOpacity onPress={this._loginAction.bind(this)}>
                            <Text style={[styles.agreementText,{fontSize:15}]}>直接登录》</Text>
                        </TouchableOpacity>
                    </View>
                </KeyboardAwareScrollView>
                <ToastTip ref="toast"/>
                <LoadingTip show={this.state.loadingShow}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
RegIndex = connectHelper(state => state)(RegIndex);

module.exports = RegIndex;
